package com.micromsg.common.core;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

//统一响应体
@Data
@NoArgsConstructor
public class ApiResult<T> {

    @ApiModelProperty("状态码")
    private int code;

    @ApiModelProperty("返回信息")
    private String message;

    @ApiModelProperty("返回实体")
    private T data;

    public ApiResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(200, "请求成功", data);
    }

//    public static <T> ApiResult<T> error(int code, String message) {
//        return new ApiResult<>(code, message, null);
//    }

    public static <T> ResponseEntity<ApiResult<T>> ok(T data) {
        return new ResponseEntity(new ApiResult(200, "请求成功", data), HttpStatus.OK);
    }

    public static ResponseEntity<ApiResult<Object>> ok() {
        return new ResponseEntity(new ApiResult(200, "请求成功", null), HttpStatus.OK);
    }

    public static <T> ResponseEntity<ApiResult<T>> error(Throwable throwable) {
        String stackTrace = ExceptionUtils.getStackTrace(throwable);
        String message = throwable.getCause() != null ? throwable.getCause().getMessage() : throwable.getMessage();
        ApiResult apiResult = new ApiResult(500, message, stackTrace);
        return ResponseEntity.status(500).body(apiResult);
    }

    public static <T> ResponseEntity<ApiResult<T>> error(int status, String message) {
        ApiResult apiResult = new ApiResult(status, message, null);
        return ResponseEntity.status(status).body(apiResult);
    }
}
